#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

#include "gs.h"
#include "init.h"
#include "dgl.h"
#include "vr.h"
#include "leak.h"
#include "tank.h"
#include "alarm.h"
#include "oilling.h"
#include "compensated.h"
#include "hctable.h"
#include "jiaojie.h"


//#define __TEST__

/* dacq thread */
static pthread_t g_dacq;
// static pthread_t g_tmp;

#if 0
static void* test_loop(void* add_data)
{
    GS_TANK* tank;
    static int index;

    while (1)
    {
        sleep(1);
        tank = &g_gs.tanks[index];

        tank->oil = rand() % 9000 + 1000;
        tank->water = rand() % 2000;
        tank->temp = rand() % 1000 - 500;
        g_gs.data_callback(tank, NULL);

        index = (index + 1) % g_gs.nr_tanks;
    }
}
#endif

static void gsd_save_data(GS_TANK *tank)
{
}


static void gsd_leak(GS_TANK *tank)
{
    /* Send leak message to save */

    /* Send leak message to GUI */
    if (gs_leak_callback)
        gs_leak_callback(tank);
}

static void gsd_oilling(GS_TANK *tank)
{
    /* Send oilling message to save */
    // gs_oilling_save(tank);

    /* Send oilling message to GUI */
    if (gs_oilling_callback)
        gs_leak_callback(tank);
}

static void* dacp_loop(void* add_data)
{
    int ret;
    GS_TANK *tank;

    static int curr = 0;

    while(1) {
//        printf ("%s Current tank index = %d\n", __FUNCTION__, curr);

        /* Get current tank */
        tank = &g_gs.tanks[curr];

        /* Get tank data */
        ret = gs_tank_data(tank);
        
        /* Data is ok, do something */
        if (ret == 0) {
            /* Save tank data */
            gsd_save_data(tank);

            /* Leak */
            gsd_leak(tank);

            /* Oilling */
            gsd_oilling(tank);

        }

        /* Get next tank index */
        curr = (curr + 1) % g_gs.tanks_nr;
    }

}

int gs_init(const char* dev)
{
    int ret; 

    ret = gs_dgl_init(dev);
    if (ret != 0) {
        fprintf(stderr, "dacq init failure\n");
        return -1;
    }

    gs_alarm_init();

    gs_jiaojie_init();

    gs_oilling_init();

    gs_leak_init();

    ret = gs_hctable_init();
    if (ret != 0)
        return -2;

#if 0
    ret = gs_compensated_init();
    if (ret != 0)
        return -3;

    ret = gs_leak_init();
    if (ret != 0)
        return -4;
#endif

    pthread_create (&g_dacq, NULL, dacp_loop, NULL);

#ifndef __TEST__
    pthread_create (&g_tmp, NULL, test_loop, NULL);
#endif

    return 0;
}

